package com.amc.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.amc.common.constant.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Enumeration;

/**
 * 请求工具类
 *
 * @author ZhangXX
 * @date @2021/10/15 15:58
 */
public class RequestUtils {

    public static String getRequestJsonString(HttpServletRequest request) throws IOException {
        String method = request.getMethod();
        if (method.equals(RequestMethod.GET.name())) {
            if (StringUtils.isEmpty(request.getQueryString())) {
                return null;
            }

            return URLDecoder.decode(request.getQueryString(), Constants.UTF8);
        } else {
            return getRequestPostStr(request);
        }
    }

    public static String getRequestPostStr(HttpServletRequest request) throws IOException {

        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = Constants.UTF8;
        }
        // 表单提交
        if (StringUtils.contains(request.getContentType(), MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
            Enumeration<String> names = request.getParameterNames();
            JSONObject jsonObject = new JSONObject();
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                jsonObject.put(name, request.getParameter(name));
            }
            return jsonObject.toJSONString();
        }
        // json提交
        byte[] buffer = getRequestPostBytes(request);

        return new String(buffer, charEncoding);

    }

    public static byte[] getRequestPostBytes(HttpServletRequest request) throws IOException {
        int contentLength = request.getContentLength();
        if (contentLength < 0) {
            return null;
        }
        byte[] buffer = new byte[contentLength];
        for (int i = 0; i < contentLength; ) {
            int readLen = request.getInputStream().read(buffer, i, contentLength - i);
            if (readLen == -1) {
                break;
            }
            i += readLen;
        }
        return buffer;
    }

    public static String getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                return cookie.getValue();
            }
        }
        return "";
    }
}
